<template>
	<div class="mine">
		<h1>头像</h1>
		<div class="mine-item">
			<p class="mine-avatar" @click="takePhoto">
				<img :src="faceImageFile ? faceImageFile : 'https://newmefit.cn/resource/gym/base/base3.jpg'" class="mine-img" mode="aspectFill"><i class="micon-1"></i>
			</p>
			<uni-icons type="close" size="18" class="icon-close" @click.prevent.stop="deleteFaceImage" color='red' v-if="!checkFaceImageFileId"></uni-icons>
		</div>
		<h1>基础信息</h1>
		<div class="mine-item">
			<p><span>手机号</span><span>{{ memberData.phone }}</span></p>
			<p>
				<span>姓名</span>
				<input class="uni-input" placeholder="姓名" v-model="memberData.userName" :disabled="false" type="text"/>
				<em><i class="micon-1"></i></em>
			</p>
			<p>
				<span>性别</span>
				<uni-data-checkbox :localdata="genderArr" v-model="memberData.gender" :disabled="false"></uni-data-checkbox>
			</p>
		</div>
		<h1>详细资料</h1>
		<div class="mine-item">
			<p>
				<span>身份证号</span>
				<input class="uni-input" placeholder="身份证号" v-model="memberData.idCard" :disabled="true"/>
				<em><i class="micon-1"></i></em>
			</p>
			<p>
				<span>紧急联系人</span>
				<input class="uni-input" placeholder="紧急联系人" v-model="memberData.emergencyContact" :disabled="false" type="text"/>
				<em><i class="micon-1"></i></em>
			</p>
			<p>
				<span>紧急联系人手机号</span>
				<input class="uni-input" placeholder="紧急联系人手机号" v-model="memberData.emergencyContactPhone" :disabled="false" type="number"/>
				<em><i class="micon-1"></i></em>
			</p>
		</div>
		<div class="footer">
      <span class="next" @click="submit">确认</span>
    </div> 
	</div>
</template>

<script>
import { mapGetters } from 'vuex'
import { memberInfo, getPublicUrl, memberEdit } from '@/api/manageApi'
import { baseUrl } from '@/config/config'
export default {
	data() {
		return {
			indicatorDots: true,
			autoplay: true,
			interval: 2000,
			duration: 500,
			scrollHeight: 200,
			scrollLeft: 0,
			memberData: {},
			faceImageFile: '',
			faceImageFileId: '',
			checkFaceImageFileId: '',
			genderArr: [
				{text: '男', value: 1},
				{text: '女', value: 0}
			]
		}
	},
	computed: {
		...mapGetters(['userInfo', 'uniToken'])
	},
	onLoad() {
		this.getMemberInfo()
	},
	methods: {
		deleteFaceImage () {
      this.faceImageFileId = ''
      this.faceImageFile = ''
    },
		takePhoto() {
      // 调用uni.chooseImage API
			if(this.checkFaceImageFileId){
				return
			}
      uni.chooseImage({
        count: 1, // 默认9，设置图片的数量
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['camera'], // 可以指定来源是相机还是相册，默认二者都有
        success: (chooseImageRes) => {
          const tempFilePaths = chooseImageRes.tempFilePaths;
          this.faceImageFile = tempFilePaths[0]
          // 调用uni.uploadFile API上传图片
          var uuid = this.getuuid()
          var imgStrArr = tempFilePaths[0].split('/')
          var name = imgStrArr[imgStrArr.length - 1]
          var url = baseUrl + '/file/handle/uploadFile?explorerId=-1&parentId=-1&name=' + name + '&md5=' + uuid
          uni.uploadFile({
            url: url, // 服务器上传接口地址
            filePath: tempFilePaths[0],
            name: 'file', // 必须填写，后台用来接收文件
            header: {
              'Authorization': 'Bearer' + ' ' + this.uniToken,
              'Content-Type': 'multipart/form-data'
            },
            success: (uploadFileRes) => {
              console.log('upload success:', uploadFileRes)
							this.faceImageFileId = JSON.parse(uploadFileRes.data).data.fileId
							this.uShowToast('图片上传成功')
            },
            fail: (uploadFileErr) => {
              console.log('upload fail:', uploadFileErr);
              this.uShowToast('失败' + JSON.stringify(uploadFileErr))
              // 处理上传失败的结果
            }
          })
        },
        fail: (chooseImageErr) => {
          console.log('choose image fail:', chooseImageErr)
          // 处理选择图片失败的结果
        }
      })
    },
		getMemberInfo () {
			memberInfo('').then(res => {
				console.log(res)
				if (res.code == 200) {
					var data = res.data
					this.memberData = data
					this.checkFaceImageFileId = data.faceImageFileId
					if (data.faceImageFileId) {
						this.faceImageFileId = data.faceImageFileId
						getPublicUrl({fileId: data.faceImageFileId}).then(response => {
              this.faceImageFile = response.data
            })
					}
				}
			})
		},
		submit () {
			if(this.memberData.userName === '') {
				this.uShowToast('姓名不能为空')
				return
			}

			const reg = /^[^<>"'|\\%]+$/
			if (!reg.test(this.memberData.userName)) {
				this.uShowToast('姓名不能包含非法字符：< > \" \' \\\ |%')
				return
			}
			if (!reg.test(this.memberData.emergencyContact) && this.memberData.emergencyContact) {
				this.uShowToast('紧急联系人不能包含非法字符：< > \" \' \\\ |%')
				return
			}

			const reg1 = /^[0-9]\d*$/
			if (!reg1.test(this.memberData.emergencyContactPhone) && this.memberData.emergencyContactPhone) {
				this.uShowToast('手机号必须是数字')
				return
			}
			var params = {
				'userId': this.memberData.userId,
				'faceImageFileId': this.faceImageFileId,
				'birthday': '',
				'emergencyContact': this.memberData.emergencyContact,
				'emergencyContactPhone': this.memberData.emergencyContactPhone,
				'gender': this.memberData.gender,
				'idCard': this.memberData.idCard,
				'phone': this.memberData.phone,
				'portraitPictureFileId': this.memberData.portraitPictureFileId,
				'userName': this.memberData.userName
			}
			// console.log(params)
			memberEdit(params).then((res) => {
				// console.log(res)
				this.uShowToast(res.msg)
				this.getMemberInfo()
			})
		},
    getuuid (len, radix) {
      var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('')
      var chars = CHARS
      var uuid = []
      var i
      radix = radix || chars.length
      if (len) {
        for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]
      } else {
        var r
        uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'
        uuid[14] = '4'
        for (i = 0; i < 36; i++) {
          if (!uuid[i]) {
            r = 0 | Math.random() * 16
            uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]
          }
        }
      }
      return uuid.join('')
    }
	}
}
</script>

<style lang="scss">
.mine {
	.fr{
		float: right;
	}
	.micon-1{
		width: 10rpx;
		height: 18rpx;
		display: inline-block;
		background: url(../../static/right2.png) no-repeat 0 0;
		background-size: cover;
		margin-left: 20rpx;
	}
	.mine-img{
		max-width: 96rpx;
		max-height: 96rpx;
		vertical-align: middle;
		border-radius: 15rpx;
	}
	h1{
		width: 702rpx;
		margin: 32rpx auto 24rpx;
		font-weight: 400;
		font-size: 30rpx;
		color: #1E1E1E;
	}
	.mine-item{
		width: 702rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 16rpx 28rpx;
		box-sizing: border-box;
		margin: 0 auto;
		position: relative;
		.icon-close{
			position: absolute;
			left: 100rpx;
			top: 0px;
			color: red;
			font-size: 24rpx;
		}
		p{
			font-size: 30rpx;
			color: #1E1E1E;
			margin: 36rpx 0;
			display: flex;
			align-items: center;
      justify-content: space-between;
			span{
				width: 230rpx;
				display: inline-block;
				font-size: 28rpx;
				color: #838383;
			}
		}
		.uni-input{
			width: 350rpx;
			font-size: 28rpx;
			color: #838383;
			text-align: right;
		}
		.mine-avatar{
			margin: 0;
			line-height: 96rpx;
		}
	}
	.footer{
    width: 750rpx;
    height: 128rpx;
    background: #FFFFFF;
    text-align: center;
    position: fixed;
    left: 0;
    bottom: 0;
		// display: none; 
    span{
      margin-top: 24rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      display: inline-block;
      border-radius: 40rpx;
      background: #FF5D3D;
      font-size: 32rpx;
      color: #FFFFFF;
    }
    .next{
      width: 646rpx;
    }
    .pre-step{
      width: 328rpx;
      background: #FFFFFF;
      border: 1px solid #FF5A20;
      color: #FF5A20;
      margin-right: 30rpx;
    }
    .next-step{
      width: 328rpx;
    }
  }
}
</style>
